package com.gable.exhibition.controller;

import com.alibaba.fastjson.JSON;
import com.gable.common.util.HttpPost;
import com.gable.common.util.ReturnResultUtil;
import com.gable.common.util.StringUtil;
import com.gable.common.util.UUIDGenerator;
import com.gable.exhibition.model.ValidateCode;
import com.gable.exhibition.service.ValidateCodeService;
import com.gable.exhibition.util.MessageUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Lesson on 2018/2/5.
 * 发送验证码的控制器
 */
@Controller
@RequestMapping(value = "/code")
public class SendCodeController {

    Logger logger = Logger.getLogger(this.getClass());

    @Value("${validateCodeUrl}")
    private String validateCodeUrl;

    @Autowired
    ValidateCodeService validateCodeService;

        @RequestMapping(value="/sendCodeByLogin",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
        @ResponseBody
        public ReturnResultUtil SendCodeByLogin(HttpServletRequest request, HttpServletResponse response){
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String mobile = request.getParameter("mobile");
                if (StringUtil.isEmpty(mobile)) {
                    return new ReturnResultUtil(500, MessageUtil.MOBILECANNOTEMPTY);
                }
                Map bodyMap = new HashMap();
                bodyMap.put("mobile", mobile);
                ReturnResultUtil rm = HttpPost.HttpPostClient(validateCodeUrl, null, bodyMap);
                if (rm.getRet() != 200) {
                    return new ReturnResultUtil(500, rm.getMsg());
                }
                ValidateCode validateCode = new ValidateCode();
                validateCode.setId(UUIDGenerator.getUniqueLong());
                validateCode.setCreateTime(sdf.format(new Date()));
                validateCode.setCode(Integer.parseInt(rm.getData().toString()));
                validateCode.setMobile(mobile);
                ReturnResultUtil rru = validateCodeService.saveValidateCode(validateCode);
                logger.info(JSON.toJSONString(rru));
                return rru;
            }catch (Exception e){
                e.printStackTrace();
            }
            return new ReturnResultUtil(500, MessageUtil.SENDEXCEPTION);
        }
}
